<script setup>
import { reactive, ref } from "vue";
import { getLogin } from "../api/index";
import router from "@/router";
// 初始的ref
const ref_form = ref(null)

// 表单数据声明
const userInfo = reactive({
  username: '',
  password: ''
})

// 表单数据效验规则
const rules = {
  username: [{ required: true, trigger: 'blur', message: '用户名不能为空' }],
  password: [{ required: true, trigger: 'blur', message: '密码不能为空' }]
}

// 登录方法
const onLogin = () => {
  ref_form.value.validate((val) => {
    if (val) {
      getLoginData()
    } else {
      console.log('登录失败')
    }
  })
}

// 登陆接口
const getLoginData = async () => {
  // 接口调用
  const res = await getLogin({
    name: userInfo.username,
    pwd: userInfo.password,
  });
  console.log(res)
  if(res?.token){
    localStorage.setItem('token',res.token)
    ElMessage({
      message: res.message,
      type: 'success',
    })
    // 登录成功后跳转页面
    router.push('/home')
  }
}
// 跳转注册页面
const toGo = () => {
  router.push('/register')
}
</script>

<template>
  <div class="login">
    <!--  背景图片-->
    <div class="l_img1"><img src="../assets/背景1.png"></div>
    <div class="login_container">
      <h1>小吴课程管理系统</h1>
      <el-form class="login_form" :model="userInfo" :rules="rules" @keyup.enter="onLogin" ref="ref_form">
        <el-form-item prop="username">
          <!--用户名-->
          <el-input style="width: 240px" placeholder="请输入用户名" v-model.trim="userInfo.username">
            <template #prepend><el-icon><User /></el-icon></template>
          </el-input>
        </el-form-item>
        <!--密码-->
        <el-form-item prop="password">
          <el-input
              style="width: 240px"
              placeholder="请输入密码"
              show-password
              v-model.trim="userInfo.password"
          >
            <template #prepend><el-icon><Lollipop /></el-icon></template>
          </el-input>
        </el-form-item>
        <!--        登陆-->
        <el-button class="login_submit"  type="primary" @click="onLogin">登录</el-button>
        <div class="login_register" @click="toGo">去注册</div>
      </el-form>
    </div>
  </div>

</template>

<style lang="less" scoped>
.login {
  width: auto;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.l_img1 img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  z-index: -1; // 图片置于内容下方
}

.login_container {
  width: 350px;
  height: 260px;
  background-color: #ffffff;
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 10px;
  box-shadow: 5px 6px 50px rgba(0, 0, 0, 0.5);
  opacity: 0.85;
  border-radius: 8px;
  align-items: center;
  text-align: center;
}
.login_container h1{
  margin: -10px 0px 20px 0px;
}
.login_submit{
  width: 100px;
  font-size: 18px;
  margin-bottom: 10px;
}
.login_register{
  color: #409eff;
  cursor: pointer;
}
</style>